<template>
  <div id="userLoginForm">
    <h2 class="title">登录</h2>
    <div class="desc">云图库</div>
    <a-form :model="formState" name="basic" autocomplete="off" @finish="handleSubmit">
      <a-form-item
        name="userAccount"
        :rules="[
          { required: true, message: '请输入账号' },
          { min: 4, message: '账号长度不能小于4' },
        ]"
      >
        <a-input v-model:value="formState.userAccount" placeholder="这里输入账号" />
      </a-form-item>

      <a-form-item
        name="userPassword"
        :rules="[
          { required: true, message: '请输入密码' },
          { min: 8, message: '密码长度不能小于8' },
        ]"
      >
        <a-input-password v-model:value="formState.userPassword" placeholder="这里输入密码" />
      </a-form-item>
      <div class="tips">
        <router-link to="/user/register">
          <a>去注册</a>
        </router-link>
      </div>
      <!-- <a-form-item name="remember" :wrapper-col="{ offset: 8, span: 16 }">
        <a-checkbox v-model:checked="formState.remember">Remember me</a-checkbox>
      </a-form-item> -->

      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import { userLoginUsingPost } from '@/api/userController'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { message } from 'ant-design-vue'
import { reactive } from 'vue'
import { useRouter } from 'vue-router'

interface FormState {
  username: string
  password: string
  remember: boolean
}

const formState = reactive<API.UserLoginDTO>({
  userAccount: '',
  userPassword: '',
})

const router = useRouter()
const loginUserStore = useLoginUserStore()

/**
 * 提交表单
 * @param values
 */
const handleSubmit = async (values: any) => {
  const res = await userLoginUsingPost(values)
  // 登录成功，把登录态保存到全局状态中
  if (res.data.code === 0 && res.data.data) {
    await loginUserStore.fetchLoginUser()
    message.success('登录成功')
    router.push({
      path: '/',
      replace: true,
    })
  } else {
    message.error('登录失败，' + res.data.msg)
  }
}
</script>

<style scoped>
#userLoginForm {
  width: 100%;
  max-width: 360px;
  margin: 0 auto;
  padding: 30px;
  border-radius: 5%;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  margin-bottom: 32px;
}

.desc {
  text-align: center;
  margin-bottom: 20px;
  color: #888;
}

.tips {
  margin-bottom: 16px;
  margin-right: 16px;
  text-align: right;
}
</style>
